function ApplicationModel(stompClient) {
  var self = this;
  self.stompClient = stompClient;

  self.username = ko.observable();
  self.users = ko.observableArray([]);
  self.messages = ko.observableArray();

  self.connect = function() {
    stompClient.connect('', '', function(frame) {

      console.log('Connected ' + frame);
      var userName = frame.headers['user-name'];
      var queueSuffix = frame.headers['queue-suffix'];
      

      self.username(userName);
      stompClient.subscribe("/queue/chat.history", self.addHistoryMessage);
      stompClient.subscribe("/queue/errors" + queueSuffix, function(message) {
        self.pushNotification("Error " + message.body);
      });
      stompClient.subscribe("/queue/usersOnline", self.updateUsers);
      self.updateUsers();
    }, function(error) {
      console.log("STOMP protocol error " + error);
    });
  }

  self.pushNotification = function(text) {
    /*self.notifications.push({notification: text});
    if (self.notifications().length > 5) {
      self.notifications.shift();
    }*/
	console.log(text);
  }
  
  self.addHistoryMessage = function(message) {
	  var obj = JSON.parse(message.body);
	  self.messages.unshift(obj);
	  if (self.messages().length > 10) {
	      self.messages.pop();
	  }
	  //$("#chat-history").prepend("<p><i class='icon-user'></i><span class='text-info'> " + obj.username + ":</span><i class='icon-comment'></i> " + obj.text + "</p>");
  }
  
  self.sendMessage = function() {
	  var input = $("#chat-input");
	  stompClient.send('/app/chat', {}, JSON.stringify(input.val()));
	  input.val('');
	  input.focus();
  }

  self.logout = function() {
    stompClient.disconnect();
    window.location.href = "logout";
  }
  
  self.updateUsers = function() {
	  $.getJSON( "sessionInfo/usersOnline", function( data ) {
		  self.users.removeAll();
		  $.each(data, function(i, item) {
			  self.users.push(item);
		  });
	  });
  }
  //Animation
  	self.showElement = function(element) {
	  if (element.nodeType === 1) {
	    $(element).hide().fadeIn();
	  }
	};
	 
	self.hideElement = function(element) {
	  if (element.nodeType === 1) {
	   $(element).fadeOut(function() { $(element).remove(); });
	  }
	};
}
